08. Methods

Functions Heading

Methods

ND079 C1 L1 A07 Methods

Sometimes we have a block of code that we would like to re-use. For example, here is some code that multiplies two numbers to calculate the area of a rectangle:

double length = 5.0;
double width = 3.5;
double area = length * width;

This code specifically multiplies the numbers 5.0 and 3.5. But we may have an application where we frequently want to repeat this operation with a variety of numbers. To accomplish this, we can turn this code into a method:

public double findTheArea(double length, double width) {
    double area = length * width;
    return area;
}

We can then run this method by simply entering lines like these:

findTheArea(5.0, 3.5);
findTheArea(6.0, 2.5);

This is referred to as calling or invoking the method. The values (5.0, 3.5, etc.) get passed to the method and used for the parameters length and width.

Method Syntax

Methods have four parts:

  • Name. The name of the method, which we use when calling or invoking the method.
  • Parameters. The variables that we pass the values to when we call the method.
  • Method body. The chunk of code, contained within curly braces, { }, that gets run when the method is invoked.
  • Return type. The data type of the value that the method returns.

Methods vs Functions

You'll often see the words function and method used interchangeably. Although the terms are sometimes used loosely, here's the distinction:

  • A function is any block of reusable/callable code.
  • A method is a block of reusable/callable code that is attached to a class or object.

So a method is a type of function, but it's one that is associated with a class or object, whereas other functions can be executed from anywhere.

In other words, we call any block of reusable code a function, whereas only some functions are also methods. All methods are functions but not all functions are methods.

QUIZ QUESTION::

Here's our example again:

public double findTheArea(double length, double width) {
    double area = length * width;
    return area;
}

Can you label each part?

ANSWER CHOICES:



Code

What is it?

double
double area = length * width;
return area;
(double length, double width)
findTheArea
return area;
SOLUTION:

Code

What is it?

double area = length * width;
return area;
findTheArea
return area;
(double length, double width)
double